<template>
  <div class="create-activity">
    <el-card class="form-card">
      <!-- 步骤条 -->
      <div class="step-header">
        <el-steps :active="activeStep" finish-status="success" align-center>
          <el-step title="基本信息" icon="el-icon-document"></el-step>
          <el-step title="活动设置" icon="el-icon-setting"></el-step>
          <el-step title="目标受众" icon="el-icon-user"></el-step>
          <el-step title="通知设置" icon="el-icon-bell"></el-step>
        </el-steps>
      </div>

      <el-form 
        :model="formData" 
        :rules="rules"
        ref="activityForm"
        label-width="120px"
        size="medium"
      >
        <!-- 步骤1：基本信息和联系方式 -->
        <div v-show="activeStep === 0" class="step-content">
          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-document"></i>
              基本信息
            </div>
            <el-form-item label="活动标题" prop="title">
              <el-input 
                v-model="formData.title" 
                placeholder="请输入活动标题"
                style="width: 80%"
              ></el-input>
            </el-form-item>

            <el-form-item label="活动时间" prop="activityTime">
              <el-date-picker
                v-model="formData.activityTime"
                type="datetime"
                placeholder="选择活动时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 80%"
              ></el-date-picker>
            </el-form-item>

            <el-form-item label="活动地点" prop="location">
              <el-input 
                v-model="formData.location" 
                placeholder="省市区+具体地址，如：浙江省杭州市西湖区XX路XX号"
                style="width: 80%"
              >
                <template slot="prepend">
                  <i class="el-icon-location"></i>
                </template>
              </el-input>
            </el-form-item>

            <el-form-item label="简要描述" prop="briefDescription">
              <el-input 
                v-model="formData.briefDescription" 
                placeholder="请输入简要描述"
                style="width: 80%"
              ></el-input>
            </el-form-item>

            <el-form-item label="详细描述" prop="details">
              <el-input 
                type="textarea" 
                v-model="formData.details" 
                :rows="4"
                placeholder="请输入详细描述"
                style="width: 80%"
              ></el-input>
            </el-form-item>

            <el-form-item label="预算" prop="budget">
              <el-input 
                v-model="formData.budget" 
                placeholder="请输入活动预算（选填）"
                style="width: 80%"
              >
                <template slot="append">元</template>
              </el-input>
            </el-form-item>
          </div>

          <div class="form-section">
            <div class="section-title">
              <i class="el-icon-phone"></i>
              联系方式
            </div>
            <el-form-item label="联系方式类型" prop="contactType">
              <el-select 
                v-model="formData.contactType" 
                placeholder="请选择联系方式类型" 
                style="width: 80%"
              >
                <el-option label="电话" value="电话"></el-option>
                <el-option label="微信" value="微信"></el-option>
                <el-option label="电话/微信" value="电话/微信"></el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="联系方式" prop="contactInfo">
              <el-input 
                v-model="formData.contactInfo" 
                placeholder="请输入联系方式"
                style="width: 80%"
              ></el-input>
            </el-form-item>
          </div>
        </div>

        <!-- 步骤2：报名/投票设置 -->
        <div v-show="activeStep === 1" class="step-content">
          <div class="form-section">
            <div class="section-title">报名设置</div>
            <el-form-item label="是否需要报名">
              <el-switch
                v-model="formData.needRegistration"
                active-color="#409EFF"
              ></el-switch>
            </el-form-item>

            <el-form-item 
              label="报名截止时间" 
              prop="registrationDeadline"
              v-if="formData.needRegistration"
            >
              <el-date-picker
                v-model="formData.registrationDeadline"
                type="datetime"
                placeholder="选择报名截止时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </div>
          <div class="form-section">
            <div class="section-title">投票设置</div>
            <el-form-item label="是否需要投票">
              <el-switch
                v-model="formData.needVote"
                active-color="#409EFF"
              ></el-switch>
            </el-form-item>

            <template v-if="formData.needVote">
              <el-form-item label="投票主题" prop="activityVoteOptions.theme">
                <el-input v-model="formData.activityVoteOptions.theme" placeholder="请输入投票主题"></el-input>
              </el-form-item>

              <el-form-item 
                v-for="(_, index) in 4" 
                :key="index"
                :label="`选项${index + 1}`"
                :prop="`activityVoteOptions.option${index + 1}`"
              >
                <el-input 
                  v-model="formData.activityVoteOptions[`option${index + 1}`]"
                  :placeholder="`请输入选项${index + 1}`"
                ></el-input>
              </el-form-item>

              <el-form-item label="投票截止时间" prop="voteDeadline">
                <el-date-picker
                  v-model="formData.voteDeadline"
                  type="datetime"
                  placeholder="选择投票截止时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>
            </template>
          </div>
        </div>

        <!-- 步骤3：优先推荐 -->
        <div v-show="activeStep === 2" class="step-content">
          <div class="form-section">
            <div class="section-title">优先推荐</div>
            <el-form-item label="受众群体" prop="targetAudience">
              <el-cascader
                v-model="formData.targetAudience"
                :options="audienceOptions"
                :props="{
                  multiple: true,
                  value: 'dictName',
                  label: 'dictName',
                  emitPath: false
                }"
                clearable
                collapse-tags
                placeholder="请选择优先推荐标签"
                @change="handleAudienceChange"
              ></el-cascader>
            </el-form-item>

            <el-form-item label="筛选截止时间" prop="targetAudienceTime">
              <el-date-picker
                v-model="formData.targetAudienceTime"
                type="datetime"
                placeholder="选择受众筛选截止时间"
                value-format="yyyy-MM-dd HH:mm:ss"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
          </div>
        </div>

        <!-- 步骤4：通知设置 -->
        <div v-show="activeStep === 3" class="step-content">
          <div class="form-section">
            <div class="section-title">通知设置</div>
            <el-form-item label="开启提醒">
              <el-switch
                v-model="formData.notificationEnabled"
                active-color="#409EFF"
              ></el-switch>
            </el-form-item>

            <template v-if="formData.notificationEnabled">
              <el-form-item label="提醒时间" prop="notificationDeadline">
                <el-date-picker
                  v-model="formData.notificationDeadline"
                  type="datetime"
                  placeholder="选择提醒时间"
                  value-format="yyyy-MM-dd HH:mm:ss"
                  style="width: 100%"
                ></el-date-picker>
              </el-form-item>

              <el-form-item label="提醒内容" prop="notificationContent">
                <el-input 
                  type="textarea"
                  v-model="formData.notificationContent"
                  :rows="3"
                  placeholder="请输入提醒内容"
                ></el-input>
              </el-form-item>
            </template>
          </div>
        </div>

        <!-- 步骤操作按钮 -->
        <div class="step-actions">
          <el-button 
            v-if="activeStep > 0" 
            @click="prevStep"
          >上一步</el-button>
          
          <el-button 
            v-if="activeStep < 3" 
            type="primary" 
            @click="nextStep"
          >下一步</el-button>
          
          <el-button 
            v-if="activeStep === 3" 
            type="primary" 
            @click="submitForm"
          >发布活动</el-button>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { createActivity, getDictValue } from "@/api/api";

export default {
  name: 'CreateActivity',
  data() {
    return {
      activeStep: 0, // 当前步骤
      formData: {
        title: '',
        activityTime: '',
        location: '',
        briefDescription: '',
        details: '',
        budget: '',
        contactType: '',
        contactInfo: '',
        targetAudience: [],
        targetAudienceTime: '',
        needRegistration: false,  // 默认不需要报名
        registrationDeadline: '',
        needVote: false,         // 默认不需要投票
        voteDeadline: '',
        notificationEnabled: false,
        notificationDeadline: '',
        notificationContent: '',
        activityVoteOptions: {
          theme: '',
          option1: '',
          option2: '',
          option3: '',
          option4: ''
        }
      },
      audienceOptions: [],
      firstLevelOptions: [
        { dictName: '行业领域', dictType: 'industry_field' },
        { dictName: '兴趣爱好', dictType: 'self_hobbies' },
        { dictName: '个人擅长', dictType: 'personally_good' }
      ],
      hasLoadedSecondLevel: false,
      rules: {
        title: [{ required: true, message: '请输入活动标题', trigger: 'blur' }],
        activityTime: [{ required: true, message: '请选择活动时间', trigger: 'change' }],
        location: [{ required: true, message: '请输入活动地点', trigger: 'blur' }],
        briefDescription: [{ required: true, message: '请输入简要描述', trigger: 'blur' }],
        details: [{ required: true, message: '请输入详细描述', trigger: 'blur' }],
        contactType: [{ required: true, message: '请选择联系方式类型', trigger: 'change' }],
        contactInfo: [{ required: true, message: '请输入联系方式', trigger: 'blur' }],
        registrationDeadline: [{ 
          required: true, 
          message: '请选择报名截止时间', 
          trigger: 'change'
        }],
        voteDeadline: [{ 
          required: true, 
          message: '请选择投票截止时间', 
          trigger: 'change'
        }],
        'activityVoteOptions.theme': [{ 
          required: true, 
          message: '请输入投票主题', 
          trigger: 'blur'
        }],
        'activityVoteOptions.option1': [{ 
          required: true, 
          message: '请输入选项1', 
          trigger: 'blur'
        }],
        'activityVoteOptions.option2': [{ 
          required: true, 
          message: '请输入选项2', 
          trigger: 'blur'
        }]
      }
    }
  },
  created() {
    this.initAudienceOptions();
  },
  methods: {
    async initAudienceOptions() {
      // 初始化第一级选项
      this.audienceOptions = this.firstLevelOptions.map(item => ({
        ...item,
        children: []
      }));
      
      // 加载第二级数据
      await this.loadSecondLevelOptions();
    },
    
    async loadSecondLevelOptions() {
      try {
        // 为每个一级选项加载二级数据
        await Promise.all(this.audienceOptions.map(async item => {
          const secondLevelRes = await getDictValue({
            dictId: "",
            dictName: item.dictName,
            dictType: item.dictType,
            level: "2"
          });
          
          if (secondLevelRes.code === 200) {
            // 为每个二级选项预设空的三级选项数组
            item.children = (secondLevelRes.data || []).map(secondItem => ({
              ...secondItem,
              children: []
            }));
            
            // 加载三级数据
            await Promise.all(item.children.map(async secondItem => {
              const thirdLevelRes = await getDictValue({
                dictId: secondItem.dictId,
                dictName: item.dictName,
                dictType: item.dictType,
                level: "3"
              });
              
              if (thirdLevelRes.code === 200) {
                secondItem.children = thirdLevelRes.data || [];
              }
            }));
          }
        }));
        
        this.hasLoadedSecondLevel = true;
      } catch (error) {
        console.error('加载选项失败:', error);
        this.$message.error('加载选项失败');
      }
    },
    
    handleAudienceChange(value) {
      console.log('选中的受众群体:', value);
    },

    // 下一步
    async nextStep() {
      try {
        await this.validateStep(this.activeStep);
        if (this.activeStep < 3) {
          this.activeStep++;
        }
      } catch (error) {
        // 验证失败时不进行任何操作，Element UI 会自动显示错误信息
      }
    },
    // 上一步
    prevStep() {
      if (this.activeStep > 0) {
        this.activeStep--;
      }
    },
    // 验证当前步骤
    validateStep(step) {
      let fieldsToValidate = [];
      
      switch(step) {
        case 0:
          fieldsToValidate = ['title', 'activityTime', 'location', 'briefDescription', 'details', 'contactType', 'contactInfo'];
          break;
        case 1:
          if (this.formData.needRegistration) {
            fieldsToValidate.push('registrationDeadline');
          }
          if (this.formData.needVote) {
            fieldsToValidate.push('voteDeadline', 'activityVoteOptions.theme', 'activityVoteOptions.option1', 'activityVoteOptions.option2');
          }
          break;
        case 2:
          fieldsToValidate = ['targetAudience', 'targetAudienceTime'];
          break;
        case 3:
          if (this.formData.notificationEnabled) {
            fieldsToValidate = ['notificationDeadline', 'notificationContent'];
          }
          break;
      }
      
      return new Promise((resolve, reject) => {
        if (fieldsToValidate.length === 0) {
          resolve();
          return;
        }
        
        this.$refs.activityForm.validateField(fieldsToValidate, (errorMsg) => {
          if (errorMsg) {
            reject(errorMsg);
          } else {
            resolve();
          }
        });
      });
    },
    async submitForm() {
      try {
        // 验证所有步骤
        for (let i = 0; i <= 3; i++) {
          await this.validateStep(i);
        }
        
        // 处理提交数据
        const formDataToSubmit = {
          ...this.formData,
          targetAudience: Array.isArray(this.formData.targetAudience) ? this.formData.targetAudience.join(',') : ''
        };
        
        const res = await createActivity(formDataToSubmit);
        
        if (res.success) {
          this.$message.success('活动创建成功');
          this.$router.push('/activity');
        }
      } catch (error) {
        console.error('创建活动失败:', error);
        this.$message.error('表单验证失败，请检查填写的内容');
      }
    },
    resetForm() {
      this.$refs.activityForm.resetFields();
    }
  },
  watch: {
    // 监听开关状态变化，重置相关字段
    'formData.needRegistration'(newVal) {
      if (!newVal) {
        this.formData.registrationDeadline = '';
      }
    },
    'formData.needVote'(newVal) {
      if (!newVal) {
        this.formData.voteDeadline = '';
        this.formData.activityVoteOptions = {
          theme: '',
          option1: '',
          option2: '',
          option3: '',
          option4: ''
        };
      }
    }
  }
}
</script>

<style lang="less" scoped>
.create-activity {
  padding: 20px;
  background: #f5f7fa;
  min-height: 100vh;

  .form-card {
    max-width: 900px;
    margin: 0 auto;
    
    .header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .title {
        display: flex;
        align-items: center;
        gap: 8px;
        font-size: 16px;
        font-weight: 500;

        i {
          color: #409EFF;
        }
      }
    }

    .step-header {
      padding: 20px 0 40px;
    }

    .step-content {
      padding: 0 20px;
      
      .form-section {
        margin-bottom: 30px;
        
        .section-title {
          text-align: left;
          font-size: 16px;
          font-weight: 500;
          color: #303133;
          margin-bottom: 20px;
          display: flex;
          align-items: center;
          
          i {
            margin-right: 8px;
            color: #409EFF;
            font-size: 18px;
          }
        }

        :deep(.el-form-item) {
          margin-bottom: 22px;
          
          .el-form-item__label {
            text-align: left;
            padding-left: 20px;
            color: #606266;
          }

          .el-form-item__content {
            margin-left: 120px !important;
            
            .el-input-group {
              width: 80%;
            }
          }
        }

        :deep(.el-input-group__prepend) {
          background-color: #f5f7fa;
          border-color: #dcdfe6;
          color: #909399;
          padding: 0 12px;
        }
      }
    }

    .step-actions {
      display: flex;
      justify-content: center;
      gap: 16px;
      padding: 20px 0;
      border-top: 1px solid #ebeef5;
      margin-top: 20px;
    }

    :deep(.el-form-item__label) {
      font-weight: 500;
    }
  }
}

// 适配移动端
@media screen and (max-width: 768px) {
  .create-activity {
    padding: 10px;
    
    .form-card {
      .step-content {
        padding: 0 10px;
        
        .form-section {
          :deep(.el-form-item) {
            .el-form-item__label {
              padding-left: 0;
            }
            
            .el-form-item__content {
              margin-left: 0 !important;
              
              .el-input, .el-select, .el-date-picker {
                width: 100% !important;
              }
            }
          }
        }
      }
    }
  }
}

// 自定义步骤条样式
:deep(.el-steps) {
  .el-step__title {
    font-size: 14px;
  }
  
  .el-step__icon {
    width: 34px;
    height: 34px;
    
    i {
      font-size: 18px;
    }
  }
}

/deep/ .el-cascader {
  width: 100%;
  
  .el-input__inner {
    border: 1px solid #dcdfe6;
    border-radius: 4px;
    padding-left: 15px;
    font-size: 14px;
    
    &::placeholder {
      color: #999;
    }
  }
}
</style>
